<?php

namespace App\Repository\Orders;

use App\Jobs\OrderSubmit;
use App\Models\Admin\AdminUsers;
use App\Models\Anchor\AnchorModel;
use App\Models\Anchor\AnchorWorksModel;
use App\Models\CatchConf\DouYinCatchModel;
use App\Models\Orders\OrdersModel as model;
use App\Models\Orders\OrdersTransferModel;
use App\Models\Rebate\RebateLogsModel;
use App\Models\Rebate\RebateModel;
use App\Models\Service\ServiceCallModel;
use App\Repository\Api\Ip138Repository;
use App\Repository\BaseRepository;
use App\Repository\Order\OrderInfoRepository;
use App\Repository\Order\OrderLogRepository;
use App\Repository\Order\OrderProductRepository;
use App\Repository\Orders\OrdersUserRepository as newOrdersInfo;
use App\Repository\Product\GoodsRepository;
use App\Repository\Service\ServiceRepository;
use Illuminate\Support\Facades\DB;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

class OrdersRepository extends BaseRepository
{
    public $model;
    public $modelInfo;
    public $logModel;
    public $productModel;
    public $goodsModel;
    public $newOrdersInfo;
    public $log;

    public function __construct()
    {
        $this->model = new model();
        $this->modelInfo = new OrderInfoRepository();
        $this->logModel = new OrderLogRepository;
        $this->productModel = new OrderProductRepository;
        $this->goodsModel = new GoodsRepository();
        $this->newOrdersInfo = new newOrdersInfo();
        $this->log = new Logger('ordersEdit');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/ordersEdit.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        parent::__construct();
    }

//    统一处理,方便导出
    public function indexWhere($params)
    {
        //        页面数据是哪种,比如客服操作之类
        $listType = isset($params['listType']) ? intval($params['listType']) : -1;
        $where = [];
        if (isset($params['status'])) {
            if (is_string($params['status'])) {
                if ($params['status'] != '') {
                    $where['where']['orders.status'] = $params['status'];
                }
            } else if (is_array($params['status']) && !empty($params['status'])) {
                if (count($params['status']) > 1) {
                    $where['In']['orders.status'] = $params['status'];
                } else {
                    $where['where']['orders.status'] = $params['status'][0];
                }
            }
        }
//        这功能只有主店铺能查其它店的单
        if ($listType == 100) {
            if (isset($params['shop_id'])) {
//            分销商里查询,只有主店铺能查
                if ($params['user']['shop_id'] == SUPPER_SHOP_ID) {
                    if (!empty($params['shop_id'])) {
                        if (is_array($params['shop_id'])) {
                            if (count($params['shop_id']) > 1) {
                                $where['In']['orders.shop_id'] = $params['shop_id'];
                            } else {
                                $where['where']['orders.shop_id'] = $params['shop_id'][0];
                            }
                        } else {
                            $where['where']['orders.shop_id'] = $params['shop_id'];
                        }
                    }
                } else {
                    $where['where']['orders.shop_id'] = $params['user']['shop_id'];
                }
            } else {
//            只能查自己的
                if ($params['user']['shop_id'] == SUPPER_SHOP_ID) {
                    $where['neq']['orders.shop_id'] = SUPPER_SHOP_ID;
                } else {
                    $where['where']['orders.shop_id'] = $params['user']['shop_id'];
                }
            }
        } else {
//            非分销商进入的,只能查自己
            $where['where']['orders.shop_id'] = $params['user']['shop_id'];
        }
        if (isset($params['source'])) {
            if (is_string($params['source'])) {
                if ($params['source'] != '') {
                    $where['where']['orders_user.source'] = $params['source'];
                }
            } else if (is_array($params['source']) && !empty($params['source'])) {
                if (count($params['source']) > 1) {
                    $where['In']['orders_user.source'] = $params['source'];
                } else {
                    $where['where']['orders_user.source'] = $params['source'][0];
                }
            }
        }
        if (isset($params['is_sign']) && $params['is_sign'] != '') {
            if ($params['is_sign'] == 0) {
                $where['where']['orders.service_user_id'] = 0;
            } else if ($params['is_sign'] == 1) {
                $where['egt']['orders.service_user_id'] = 1;
            }
        }
//指定归属客服
        if (isset($params['service_user_id']) && !empty($params['service_user_id'])) {
            $serviceId = $params['service_user_id'];
            if (is_array($serviceId)) {
                if (count($serviceId) === 1) {
                    $where['where']['orders.service_user_id'] = $serviceId[0];
                } else {
                    $where['In']['orders.service_user_id'] = $serviceId;
                }
            } else {
                $where['where']['orders.service_user_id'] = $serviceId;
            }
        }
//        if (empty($params['is_dist'])) {
////            代理分组查询
//            if (!empty($params['dist_class']) && $params['dist_class'] != 1) {
//
//                $where['like']['orders.shop_str'] = '.' . $params['user']['shop_id'] . '.';
//            } else {
////                $where['where']['orders.shop_id'] = $params['user']['shop_id'];
//            }
//
//        }
        if (isset($params['three_msg']) && $params['three_msg'] != '') {
            $where['like']['orders.three_msg'] = $params['three_msg'];
        }
        if (isset($params['sell_name']) && $params['sell_name'] != '') {
            $where['where']['orders_user.sell_name'] = $params['sell_name'];
        }
        if (!empty($params['is_dist'])) {
            $where['like']['orders.shop_str'] = '.' . $params['user']['shop_id'] . '.';
        }
//        if (!empty($params['shop_id']) && is_string($params['shop_id'])) {
//            $where['like']['orders.shop_id_str'] = '.' . $params['shop_id'] . '.';
//        }
//        if (!empty($params['shop_id']) && is_array($params['shop_id'])) {
//            // $where['like']['orders.shop_id_str'] = '.'.$request->user->shop_id . '.' . $params['shop_id'] . '.';
//            $shopArrs = [];
//            foreach ($params['shop_id'] as $key => $v) {
//                if (!empty($v)) {
//                    // if($key == 0){
//                    //   $where['whereors']['where'][] = ['orders.shop_id_str','like','.'.$request->user->shop_id.'.'.$v.'.'];
//                    // }else{
//                    //   $where['whereors']['whereor'][] = ['orders.shop_id_str','like','.'.$request->user->shop_id.'.'.$v.'.'];
//                    // }
//                    $shopArrs[] = '.' . $v . '.';
//
//                }
//            }
//            $where['likeorall']['orders.shop_id_str'] = $shopArrs;
//        }
        if (!empty($params['ordersno'])) {
            $where['where']['orders.ordersno'] = trim($params['ordersno'], ' ');
        }
        // 多选
        if (!empty($params['more_orders'])) {
            // var_dump($params['more_orders']);
            $resOrders = [$params['more_orders']];
            if (strstr($params['more_orders'], "\n")) {
                $resOrders = explode("\n", $params['more_orders']);
            }
            if (strstr($params['more_orders'], " ")) {
                $resOrders = explode(" ", $params['more_orders']);
            }
            if (!empty($resOrders)) {
                $where['In']['orders.ordersno'] = $resOrders;
            }
        }
        // 上游单号
        if (!empty($params['more_sup_order'])) {
            // var_dump($params['more_orders']);
            $resOrders = [$params['more_sup_order']];
            if (strstr($params['more_sup_order'], "\n")) {
                $resOrders = explode("\n", $params['more_sup_order']);
            }
            if (strstr($params['more_sup_order'], " ")) {
                $resOrders = explode(" ", $params['more_sup_order']);
            }
            if (!empty($resOrders)) {
                $where['In']['orders.sup_orderno'] = $resOrders;
            }
        }
        // 外部单号
        if (!empty($params['more_dist_order'])) {
            // var_dump($params['more_orders']);
            $resOrders = [$params['more_dist_order']];
            if (strstr($params['more_dist_order'], "\n")) {
                $resOrders = explode("\n", $params['more_dist_order']);
            }
            if (strstr($params['more_dist_order'], " ")) {
                $resOrders = explode(" ", $params['more_dist_order']);
            }
            if (!empty($resOrders)) {
                $where['In']['orders_user.dist_orderno'] = $resOrders;
            }
        }
        // 生产号码
        if (!empty($params['more_iccid_order'])) {
            // var_dump($params['more_orders']);
            $resOrders = [$params['more_iccid_order']];
            if (strstr($params['more_iccid_order'], "\n")) {
                $resOrders = explode("\n", $params['more_iccid_order']);
            }
            if (strstr($params['more_iccid_order'], " ")) {
                $resOrders = explode(" ", $params['more_iccid_order']);
            }
            if (!empty($resOrders)) {
                $where['In']['orders.iccid'] = $resOrders;
            }
        }
        // 物流单号
        if (!empty($params['more_express_order'])) {
            // var_dump($params['more_orders']);
            $resOrders = [$params['more_express_order']];
            if (strstr($params['more_express_order'], "\n")) {
                $resOrders = explode("\n", $params['more_express_order']);
            }
            if (strstr($params['more_express_order'], " ")) {
                $resOrders = explode(" ", $params['more_express_order']);
            }
            if (!empty($resOrders)) {
                $where['In']['orders.express_number'] = $resOrders;
            }
        }
        // 收件号码
        if (!empty($params['more_phone_order'])) {
            // var_dump($params['more_orders']);
            $resOrders = [$params['more_phone_order']];
            if (strstr($params['more_phone_order'], "\n")) {
                $resOrders = explode("\n", $params['more_phone_order']);
            }
            if (strstr($params['more_phone_order'], " ")) {
                $resOrders = explode(" ", $params['more_phone_order']);
            }
            if (!empty($resOrders)) {
                $where['In']['orders_user.contact_phone'] = $resOrders;
            }
        }
        // 证件号
        if (!empty($params['more_idy_order'])) {
            // var_dump($params['more_orders']);
            $resOrders = [$params['more_idy_order']];
            if (strstr($params['more_idy_order'], "\n")) {
                $resOrders = explode("\n", $params['more_idy_order']);
            }
            if (strstr($params['more_idy_order'], " ")) {
                $resOrders = explode(" ", $params['more_idy_order']);
            }
            if (!empty($resOrders)) {
                $where['In']['orders_user.pay_identity'] = $resOrders;
            }
        }
        // 证件号
        if (!empty($params['more_authod_order'])) {
            // var_dump($params['more_orders']);
            $resOrders = [$params['more_authod_order']];
            if (strstr($params['more_authod_order'], "\n")) {
                $resOrders = explode("\n", $params['more_authod_order']);
            }
            if (strstr($params['more_authod_order'], " ")) {
                $resOrders = explode(" ", $params['more_authod_order']);
            }
            if (!empty($resOrders)) {
                $where['In']['orders_user.author_id'] = $resOrders;
            }
        }
        if (!empty($params['orderno'])) {
            $where['where']['orders.ordersno'] = trim($params['orderno'], ' ');
        }
        if (!empty($params['pay_identity'])) {
            $where['where']['orders_user.pay_identity'] = trim($params['pay_identity'], ' ');
        }
        if (!empty($params['sup_orderno'])) {
            $where['where']['orders.sup_orderno'] = $params['sup_orderno'];
            // $where['where'] = ['sup_orderno' => $params['sup_orderno']];
        }
        if (!empty($params['dist_orderno'])) {
            $where['where']['orders_user.dist_orderno'] = $params['dist_orderno'];
            // $where['where'] = ['sup_orderno' => $params['sup_orderno']];
        }
        if (!empty($params['iccid'])) {
            $where['where']['orders.iccid'] = $params['iccid'];
            // $where['where'] = ['sup_orderno' => $params['sup_orderno']];
        }
        if (!empty($params['express_number'])) {
            $where['where']['orders.express_number'] = $params['express_number'];
            // $where['where'] = ['sup_orderno' => $params['sup_orderno']];
        }
        if (!empty($params['contact_phone'])) {
            $where['where']['orders_user.contact_phone'] = $params['contact_phone'];
            // $where['where'] = ['sup_orderno' => $params['sup_orderno']];
        }
        if (!empty($params['contact_name'])) {
            $where['where']['orders_user.contact_name'] = $params['contact_name'];
            // $where['where'] = ['sup_orderno' => $params['sup_orderno']];
        }
        if (!empty($params['goods_id']) && empty($params['is_dist'])) {
            $where['In']['orders.goods_id'] = $params['goods_id'];
            // $where['where'] = ['sup_orderno' => $params['sup_orderno']];
        }
        if (!empty($params['goods_id']) && !empty($params['is_dist']) && is_string($params['goods_id'])) {
            $where['like']['orders.sup_goods_id_str'] = $params['goods_id'];
            // $where['where'] = ['sup_orderno' => $params['sup_orderno']];
        }
        if (!empty($params['goods_id']) && !empty($params['is_dist']) && is_array($params['goods_id'])) {
            // $where['like']['orders.sup_goods_id_str'] = $params['goods_id'];
            $where['likeorall']['orders.sup_goods_id_str'] = $params['goods_id'];
            // foreach($params['goods_id'] as $key => $v){
            //   if(!empty($v)){
            //     // if($key == 0){
            //     //   $where['whereors']['where'][] = ['orders.sup_goods_id_str','like','.'.$v.'.'];
            //     // }else{
            //     //   $where['whereors']['whereor'][] = ['orders.sup_goods_id_str','like','.'.$v.'.'];
            //     // }

            //   }
            // }
            // $where['where'] = ['sup_orderno' => $params['sup_orderno']];
        }
        if (!empty($params['channel_id']) && !empty($params['channel_id']) && is_array($params['channel_id'])) {
            $where['In']['orders.sup_id'] = $params['channel_id'];
            // $where['where'] = ['sup_orderno' => $params['sup_orderno']];
        }
        if (!empty($params['channel_id']) && !empty($params['channel_id']) && is_string($params['channel_id'])) {
            $where['where']['orders.sup_id'] = $params['channel_id'];
            // $where['where'] = ['sup_orderno' => $params['sup_orderno']];
        }
        if (!empty($params['author_id'])) {
            $where['where']['orders_user.author_id'] = $params['author_id'];
            // $where['where'] = ['sup_orderno' => $params['sup_orderno']];
        }
        if (!empty($params['product_id']) && is_array($params['product_id'])) {

            $where['In']['orders.product_id'] = $params['product_id'];
            // $where['where']['orders.product_id'] = $params['product_id'];
            // $where['where'] = ['sup_orderno' => $params['sup_orderno']];
        }
        if (!empty($params['product_id']) && is_string($params['product_id'])) {
            $where['where']['orders.product_id'] = $params['product_id'];
            // $where['where']['orders.product_id'] = $params['product_id'];
            // $where['where'] = ['sup_orderno' => $params['sup_orderno']];
        }
//        if ((isset($params['is_trun']) && ($params['is_trun'] != '']) {
//            $where['where']['orders.type'] = $params['is_trun'];
//            // $where['where'] = ['sup_orderno' => $params['sup_orderno']];
//        }
//        快递查询
        if (!empty($params['express_status']) && is_array($params['express_status'])) {
            $where['In']['orders.express_status'] = $params['express_status'];
        }
        if (!empty($params['express_status']) && is_string($params['express_status'])) {
            $where['where']['orders.express_status'] = $params['express_status'];
        }
        // var_dump($where);
        if (!empty($params['province'])) {
            $where['like']['orders_user.post_province'] = $params['province'];
        }
        if (!empty($params['city'])) {
            $where['like']['orders_user.post_city'] = $params['city'];
        }
        if (!empty($params['tagging']) && is_array($params['tagging'])) {
            $where['In']['orders_user.tagging'] = $params['tagging'];
        }
        if (!empty($params['tagging']) && is_string($params['tagging'])) {
            $where['where']['orders_user.tagging'] = $params['tagging'];
        }
//        if (!empty($params['dist_class']) && $params['dist_class'] != 1) {
//            // 通过
//            $resDistClass = DB::table('dist_class')->where(['dept_id' => $params['dist_class']])->first();
//            if (!$resDistClass) {
//                return $this->returnMsg(109, '代理分组未查询到');
//            }
//            if (!empty($resDistClass->dist_id)) {
//                $resDistClassArr = explode(',', trim($resDistClass->dist_id, ','));
//                //
//                if (count($resDistClassArr) > 2) {
//                    foreach ($resDistClassArr as $key => $v) {
//                        if (!empty($v) && $v != 1) {
//                            if ($key == 2) {
//                                $where['whereors']['where']['orders.shop_id'] = $v;
//                            } else {
//                                $where['whereors']['whereor']['orders.shop_id'][] = $v;
//                            }
//                        }
//
//                    }
//                }
//                if (count($resDistClassArr) < 2) {
//                    foreach ($resDistClassArr as $key => $v) {
//                        if (!empty($v) && $v != 1) {
//                            $where['where']['orders.shop_id'] = $v;
//                        }
//
//                    }
//                }
//
//            }
//
//        }
        // 最后一次转单
//        if (!empty($params['end_nums'])) {
//            if (!empty($params['dateRange'])) {
//                // $time = $params['dateRange'];
//                $where['between'] = ['orders_user.created_at' => $params['dateRange']];
//            }
//            if (!empty($params['end_nums']] && $params['end_nums'] == 2) {
//                $where['where']['orders.end_nums'] = 1;
//            } else {
//                $where['where']['orders.nums'] = 1;
//            }
//        }
        // 是否在网
        if (!empty($params['is_online'])) {
            $where['where']['is_online'] = $params['is_online'];
            $where['where']['status'] = 40;
        }
//        是否激活
        if (isset($params['activat_status']) && $params['activat_status'] != '') {
            $activatStatus = intval($params['activat_status']);
            if ($activatStatus == 1) {
//                已激活
                $where['egt']['activat_status'] = 1;
            } else {
                $where['where']['activat_status'] = 0;
            }
        }
        // 审核状态
        if (isset($params['data_review_status']) && $params['data_review_status'] != '') {
            $dataReviewStatus = intval($params['data_review_status']);
            $where['where']['data_review_status'] = $dataReviewStatus;
        }
        //        是否充值
        if (isset($params['first_status']) && $params['first_status'] != '') {
            $activatStatus = intval($params['first_status']);
            if ($activatStatus == 1) {
                $where['egt']['first_status'] = 1;
            } else {
                $where['where']['first_status'] = 0;
            }
        }
//        充值金额
        if (isset($params['first_money']) && $params['first_money'] != '') {
            $firstMoneyList = config('card.firstMoneyList');
            $firstMoneyItemKey = intval($params['first_money']);
            $firstMoneyItem = $firstMoneyList[$firstMoneyItemKey];
            if ($firstMoneyItem['symbol'] != 'between') {
                $where[$firstMoneyItem['symbol']]['orders.first_money'] = $firstMoneyItem['value'];
            } else {
                $where['between']['orders.first_money'] = $firstMoneyItem['value'];
            }
//            print_r($where);
        }
        #svar_dump($where);
//        搜索sku靓号
        if (!empty($params['sku_number'])) {
            $where['where']['orders_user.sku_number'] = $params['sku_number'];
        }
        if (!empty($params['product_type']) && is_array($params['product_type'])) {
            $where['In']['orders.product_operator'] = $params['product_type'];
        }
        if (!empty($params['product_operator']) && is_array($params['product_operator'])) {
            $where['like']['orders.product_type'] = $params['product_operator'];
        }
        // var_dump($where);
//时间验证
        if (!empty($params['dateRange']) && empty($params['end_nums'])) {
            $dateRangeField = 'orders.created_at';
            if (isset($params['dateRangeType'])) {
                if ($params['dateRangeType'] == 1) {
                    $dateRangeField = 'orders.activat_at';
                } else if ($params['dateRangeType'] == 2) {
                    $dateRangeField = 'orders.first_status_at';
                }
            }
            $where['between'][$dateRangeField] = $params['dateRange'];
        }
//        快速查询的条件
        if (isset($params['quickType'])) {
//            重新定义
            $where = [];
            $where['where']['orders.shop_id'] = $params['user']['shop_id'];
            switch (intval($params['quickType'])) {
                case 1:
//                    审核订单(提交上游没出快递单号的订单)
                    $where['where']['orders.status'] = 1;
                    $where['where']['orders.express_number'] = '';
                    break;
                case 2:
//                    跟进中订单(提交上游出快递单号的订单)
                    $where['where']['orders.status'] = 1;
                    $where['neq']['orders.express_number'] = '';
                    break;
                case 3:
//                    失败订单(订单状态失败)
                    $where['where']['orders.status'] = 60;
                    break;
                case 4:
//                    已激活订单: 激活未充值订单
                    $where['where']['orders.activat_status'] = 1;
                    $where['where']['orders.first_status'] = 0;
                    break;
                case 5:
//                    已充值订单:激活已充值订单
                    $where['where']['orders.activat_status'] = 1;
                    $where['egt']['orders.first_status'] = 1;
                    break;
                case 6:
//                    充值达标订单（就是每个产品我们要设置充值金额达标）
                    $where['raw'] = '`card_orders`.`first_money`>0 and `card_orders`.`passing_money`';
                    break;
                default:
                    break;
            }
        }
//        var_dump($where);
        // var_dump($where);
        $where['limit']['start'] = ($params['pageNum'] - 1) * $params['pageSize'];
        $where['limit']['number'] = $params['pageSize'];
        $where['join'] = [
            ['table' => 'orders_user', 'left' => 'id', 'right' => 'orders.orders_user_id'],
//            ['table' => 'douyin_catch', 'left' => 'dist_orderno', 'right' => 'orders_user.dist_orderno']
        ];

        $where['select'] = [
            'orders_user.*',
            'orders.*',
            'orders_user.remark as reason',
//            'douyin_catch.package_name as skumark',
//            'douyin_catch.skumark_remark'
        ];

        switch ($listType) {
            case 1:
//                客服操作自己的单
                $where['where']['orders.service_user_id'] = $params['user']['id'];
                break;
            case 2:
//                流转到我处理的订单
                $where['where']['orders_transfer.users_id'] = $params['user']['id'];
                $where['where']['orders_transfer.status'] = 0;
                $where['join'][] = ['table' => 'orders_transfer', 'left' => 'orders_id', 'right' => 'orders.id'];
                $where['select'][] = "orders_transfer.remark AS transfer_remark";
                break;
//                数据审核订单
            case 3:
                $where['where']['orders.data_review_status'] = 1;
                break;
            //分销商订单,只能看自己的,where在上面做限制
            case 100:
//                if ($params['user']['shop_id'] == SUPPER_SHOP_ID) {
//                    $where['neq']['orders.shop_id'] = SUPPER_SHOP_ID;
//                } else {
//                    $where['where']['orders.shop_id'] = $params['user']['shop_id'];
//                }
                break;
        }
        return $where;
    }

    //列表,isEny是指是否导出
    public function index($where, $shopId = 0, $isEny = false, $listType = 0)
    {
        $cron = $where;
        $cron['order'] = ['orderby' => 'orders_user.id', 'orderdir' => 'desc'];
        // $cron['where'] = $where;
        // var_dump($cron,111111111);
        // var_dump($cron, 444444444);
        // DB::connection()->enableQueryLog();
        $data = $this->search($this->model, $cron);
//        $data['sql'] = $this->getLastSql();
        $authorIds = [];
        $worksTimesRange = [];
        if (isset($cron['between']['orders.created_at'])) {
            $worksTimesRange = $cron['between']['orders.created_at'];
        }
        if (!empty($data['data']) && !empty($shopId)) {
            $ids = [];
            $usersIds = [];
            $distOrderno = [];
            $productIds = [];
            foreach ($data['data'] as $key => &$val) {
                //               收集订单号,订单号用来再查一些其它数据
                $ids[] = $val['id'];
                $productIds[] = $val['product_id'];
                if ($isEny) {
                    if (!empty($val['author_id'])) {
                        $authorIds[] = $val['author_id'];
                    }
                }
//                查询账号名字
                if (!empty($val['service_user_id']) && $val['service_user_id'] > 0) {
                    $usersIds[] = $val['service_user_id'];
                }
//                数据审核员
                if (!empty($val['data_review_user_id']) && $val['data_review_user_id'] > 0) {
                    $usersIds[] = $val['data_review_user_id'];
                }
                if (strtotime($val['created_at']) < strtotime('2023-12-23')) {
//                            查旧的
                    $distOrderno[] = $val['dist_orderno'];
                }
            }
            $productIds = array_unique($productIds);
            $authorIds = array_unique($authorIds);
            $ModelUsers = new AdminUsers();
//            查找最后的流转信息
            $transferArr = [];
            if ($listType !== 2 && !empty($ids)) {
                $ModelTransfer = new OrdersTransferModel();
                foreach ($ModelTransfer->from($ModelTransfer->getTable() . ' AS a')
                             ->leftJoin($ModelUsers->getTable() . ' AS b', 'a.users_id', '=', 'b.id')
                             ->select('a.orders_id', 'b.nick_name', 'a.status')
                             ->whereIn('a.orders_id', $ids)
                             ->orderBy('a.id', 'desc')
                             ->cursor() as $row) {
                    if (!isset($transferArr[$row->orders_id])) {
                        $transferArr[$row->orders_id] = $row;
                    }
                }

            }
            $usersName = [];
            //                查询相关的账号名称
            if (!empty($usersIds)) {
                $rows = $ModelUsers->whereIn('id', $usersIds)->select(['id', 'nick_name'])->get()->toArray();

                foreach ($rows as $k => $row) {
                    $usersName[$row['id']] = $row['nick_name'];
                }
            }
//            主播开场数据
            $ModelAnchorWorks = new AnchorWorksModel();
            $ModelAnchor = new AnchorModel();
            $anchorWorksRows = [];
            if (false === $isEny) {
////            客服通话记录数据,取最后一条
                $ModelServiceCall = new ServiceCallModel();
                $rows = $ModelServiceCall->select(['id', 'orders_id', 'nickname', 'created_at', 'record', 'talk_time', 'remark', 'label_name'])
                    ->where([['status', '>', 0]])
                    ->whereIn('orders_id', $ids)
                    ->orderByDesc('id')->get()->toArray();
//                echo $this->getLastSql();
                $calls = [];
                foreach ($rows as $vals) {
                    if (isset($calls[$vals['orders_id']])) {
//                        统计次数
                        $calls[$vals['orders_id']]['few'] += 1;
                        //        只要最后一个,用groupby查有问题,就循环吧.数据也不多
                        if ($calls[$vals['orders_id']]['id'] < $vals['id']) {
                            $calls[$vals['orders_id']] = $vals;
                        }
                    } else {
                        $vals['few'] = 1;
                        $calls[$vals['orders_id']] = $vals;
                    }
                }
                if (!empty($distOrderno)) {
                    $ModelDouyin = new DouYinCatchModel();
                    $rows = $ModelDouyin->whereIn('dist_orderno', $distOrderno)->select(['dist_orderno', 'package_name', 'skumark_remark'])->get()->toArray();
                    foreach ($rows as $row) {
                        $distOrdernoArr[$row['dist_orderno']] = $row;
                    }
                }
                unset($rows);
            } else {
//                导出时查询达人所在的主播开播数据
                //        查询条件
                $anchorWorkWhere = [];
                if (!empty($worksTimesRange)) {
                    $anchorWorkWhere['between']['a.created_at'] = [$worksTimesRange];
                }
                if (!empty($authorIds)) {
                    if (count($authorIds) > 1) {
                        $anchorWorkWhere['in']['a.author_id'] = $authorIds;
                    } else {
                        $anchorWorkWhere['eq']['a.author_id'] = $authorIds[0];
                    }
                }
//必须orderByDesc('a.created_at')
                foreach ($ModelAnchorWorks->from($ModelAnchorWorks->getTable() . ' AS a')
                             ->leftJoin($ModelAnchor->getTable() . ' AS b', 'a.anchor_id', '=', 'b.id')
                             ->select('a.*', 'b.nickname AS anchor_name')
                             ->searchWhere($anchorWorkWhere)
                             ->orderByDesc('a.created_at')
                             ->cursor() as $row) {
                    $anchorWorksRows[] = $row;
                }
//                print_r($anchorWorksRows);
            }
            $rebateRulesRows = $rebateLogsRows = $rebateLogsTipsRows = $rebateLogsTotalRows = [];
            if (false === $isEny) {
                // 返费规则
                $ModelRebate = new RebateModel();
                foreach ($ModelRebate->with(["rules" => function ($query) {
                    $query->select(['rebate_id', 'month', 'money']);
                }])->select(['id', 'product_id', 'effective_at', 'instantly_money'])
                             ->whereIn("product_id", $productIds)->get() as $row) {
                    $tmpArr = [];
                    if ($row->instantly_money > 0) {
                        $tmpArr[] = '立返:' . $row->instantly_money;
                    }
                    if (!empty($row->rules)) {
                        foreach ($row->rules as $r) {
                            $tmpArr[] = 'T' . $r['month'];// . ':' . $r['money'];
                        }
                    }
                    $rebateRulesRows[$row['product_id']] = implode(";", $tmpArr);
                };
                //已返费
                $ModelRebateLogs = new RebateLogsModel();
                foreach ($ModelRebateLogs->whereIn('orders_id', $ids)->select(['ordersno', 'money', 'rebate_at', 'type', 'month'])->cursor() as $row) {
                    $tmpLog = '';
                    if ($row->type == 0) {
                        $tmpLog = '立返:' . $row->money;

                    } else {
                        $tmpLog = 'T' . $row->month . ':' . $row->money;
                    }
                    if (isset($rebateLogsTotalRows[$row->ordersno])) {
                        $rebateLogsTotalRows[$row->ordersno] += $row->money;
                    } else {
                        $rebateLogsTotalRows[$row->ordersno] = $row->money;
                    }
                    $rebateLogsTipsRows[$row->ordersno][] = date("Y-m-d", strtotime($row->rebate_at)) . '返费:' . $row->money;
                    $rebateLogsRows[$row->ordersno][] = $tmpLog;
                }
            }
            $Ip138 = new Ip138Repository();
            foreach ($data['data'] as $key => &$val) {
                //加入返费规则与记录
                $val['rebate_rules'] = $rebateRulesRows[$val['product_id']] ?? '';
                $val['rebate_logs'] = '';
                if (isset($rebateLogsRows[$val['ordersno']]) && !empty($rebateLogsRows[$val['ordersno']])) {
                    $val['rebate_logs'] = implode(";", $rebateLogsRows[$val['ordersno']]);
                    $val['rebate_logs_tips'] = implode("<br />", $rebateLogsTipsRows[$val['ordersno']]);
                    $val['rebate_logs_tips'] .= '<br />总返费:' . $rebateLogsTotalRows[$val['ordersno']];
                }
//                主播数据
                $val['anchor_name'] = '';
                $val['anchor_created_at'] = '';
                $val['anchor_over_at'] = '';
                if ($isEny) {
                    $worksOpening = $ModelAnchorWorks->getOrdersAuthorInAnchorWorks($anchorWorksRows, $val['author_id'], $val['created_at']);
                    if (!empty($worksOpening)) {
                        $val['anchor_name'] = $worksOpening['anchor_name'];
                        $val['anchor_created_at'] = $worksOpening['created_at'];
                        $val['anchor_over_at'] = $worksOpening['over_at'];
                    }
                }
                //归属客服
                $val['service_user_name'] = '';
                if (!empty($val['service_user_id'])) {
                    $val['service_user_name'] = $usersName[$val['service_user_id']] ?? '';
                }
//                数据审核员
                $val['data_review_user_name'] = '';
                if (!empty($val['data_review_user_id'])) {
                    $val['data_review_user_name'] = $usersName[$val['data_review_user_id']] ?? '';
                }
//                最后流转帐号
                $val['transfer_user_name'] = '';
                if (isset($transferArr[$val['id']]) && $transferArr[$val['id']]['status'] === 0) {
                    $val['transfer_user_name'] = $transferArr[$val['id']]['nick_name'];
                }
//                导出 数据是时不用这些数据
                if (false === $isEny) {
                    $val['calls'] = $calls[$val['id']] ?? [];
//                skumark抽取手机号
//                    $val['skumark'] = $val['sku_number'];
                    if (!empty($val['sku_number'])) {
                        $val['skumark'] = $val['sku_number'];
                    } else {
                        $val['skumark'] = $val['package_name'];
//                        旧的数据处理
                        if (!empty($distOrdernoArr[$val['dist_orderno']])) {
                            $packageName = $distOrdernoArr[$val['dist_orderno']]['package_name'];
                            $val['sku_area'] = $distOrdernoArr[$val['dist_orderno']]['skumark_remark'];
                            preg_match('/([0-9]{11,13})/', $packageName, $tmp);
                            $val['sku_number'] = $val['skumark'] = $packageName;
                            if (!empty($tmp)) {
                                $val['sku_number'] = $val['skumark'] = $tmp[1];
                            }
                        }
                    }

                    $val['ip138'] = '';
                    if (!empty($val['sku_number']) && empty($val['sku_area'])) {
                        $val['ip138'] = $Ip138->getCheckMobileJsUrl($val['sku_number']);
                    }
                }
                if (!empty($val['shop_id_str'])) {
                    $shopArr = explode('.', $val['shop_id_str']);
                    if ($shopArr[0] != $shopId) {
                        $val['sup_name'] = $val['sup_shop_name'];
                        $val['sup_shop_id'] = 0;
                        $val['sup_orderno'] = '';
                    }
                }
                // var_dump(strlen($val['pay_name'])-1);
                // var_dump(mb_substr($val['pay_name'],-2,strlen($val['pay_name'])-1));
                $phoen = $val['pay_phone'];
//                if (empty(env('IS_ENCRYP')) || env('IS_ENCRYP') != 2) {
//                    if (mb_strlen($val['contact_name']) <= 2) {
//                        $val['pay_name'] = str_replace(mb_substr($val['pay_name'], -1, mb_strlen($val['pay_name']) - 1), '***', ($val['pay_name']));
//                        $val['contact_name'] = str_replace(mb_substr($val['contact_name'], -1, mb_strlen($val['contact_name']) - 1), '***', ($val['contact_name']));
//                    } else {
//                        $val['pay_name'] = str_replace(mb_substr($val['pay_name'], -2, mb_strlen($val['pay_name']) - 1), '***', ($val['pay_name']));
//                        $val['contact_name'] = str_replace(mb_substr($val['contact_name'], -2, mb_strlen($val['contact_name']) - 1), '***', ($val['contact_name']));
//                    }
//
//                    $val['pay_identity'] = str_replace(mb_substr($val['pay_identity'], 3, 11), '***', ($val['pay_identity']));
////                    $val['pay_phone'] =str_replace(mb_substr($val['pay_phone'], 3, 4), '***', ($val['pay_phone']));
//                    $val['contact_phone'] = str_replace(mb_substr($val['contact_phone'], 3, 4), '***', ($val['contact_phone']));
//                    $val['post_address'] = str_replace(mb_substr($val['post_address'], 4, mb_strlen($val['post_address']) - 4), '***', ($val['post_address']));
//                }
                $val['pay_phones'] = '';
                if ($isEny) {
                    $val['pay_phones'] = $phoen;
                }
            }
        }
        return $data;
    }

    //添加  数据
    public function add($data)
    {

        //必填 字段
        // $data['orders_user_id'] = $userId;
        if (!empty($data['orderno'])) {
            $data['ordersno'] = $data['orderno'];
        }
        $mustField = [
            'ordersno',
        ];
        $optionalFields = $this->model->getTableField();
        $msgField = [
            'ordersno' => '订单编号不能为空',
        ];
        $insertData = $this->getRealData($data, $mustField, $optionalFields, $msgField);
        if (!empty($insertData) && is_string($insertData)) {
            //返回错误参数
            return $this->returnMsg(
                2,
                $insertData
            );
        }
        // if (!empty($insertData['status'])) {
        //   $insertData['status_desc'] = $this->model->getOrderStatusDesc($insertData['status']);
        // }
        // if (!empty($insertData['source'])) {
        //   $insertData['source_type'] = $this->model->getOrderSource($insertData['source']);
        // }
        // 订单表插入
        if (!empty($insertData['status'])) {
            $insertData['status_desc'] = $this->model->getOrderStatusDesc($insertData['status']);
        }
        if (!empty($insertData['shop_id_str'])) {
            // $insertData['shop_id_str'] = substr_replace('0.', '', $insertData['shop_id_str'], 1);
            $insertData['shop_id_str'] = substr_replace($insertData['shop_id_str'], '', 0, 2);
        }
        if (empty($insertData['shop_id_str'])) {
            $insertData['shop_id_str'] = $insertData['shop_id'];
        }
        if (!empty($insertData['sup_goods_id_str'])) {
            // $insertData['sup_goods_id_str'] = substr_replace('0.', '', $insertData['sup_goods_id_str'], 1);
            $insertData['sup_goods_id_str'] = substr_replace($insertData['sup_goods_id_str'], '', 0, 2);
        }
        if (empty($insertData['sup_goods_id_str'])) {
            $insertData['sup_goods_id_str'] = $insertData['goods_id'];
        }
        if (!empty($insertData['shop_name_str'])) {
            // $insertData['shop_name_str'] = substr_replace('0.', '', $insertData['shop_name_str'], 1);
            $insertData['shop_name_str'] = substr_replace($insertData['shop_name_str'], '', 0, 2);
        }
        if (empty($insertData['shop_name_str'])) {
            $insertData['shop_name_str'] = $insertData['shop_name'];
        }
        $insertData['created_at'] = date('Y-m-d H:i:s');
        $insertData['one_product_code'] = $insertData['product_code'];
        $insertData['one_product_name'] = $insertData['product_name'];
        $insertData['one_product_id'] = $insertData['product_id'];
        $insertData['end_nums'] = 1;
        if (empty($insertData['pay_money'])) {
            unset($insertData['pay_money']);
        }
        $ordersId = $this->model->insertGetId($insertData);
        // 先添加 orders 然后在添加 orders_info
        $data['orders_id'] = $ordersId;

        // 记录用户的信息
        $userArr = $this->newOrdersInfo->add($data);
        $userId = 0;
        if (!empty($userArr['code']) && $userArr['code'] == 200) {
            $userId = $userArr['data']['id'];
        }
        if (empty($userArr['code']) || $userArr['code'] != 200) {
            return $userArr;
        }
        // 将 order里面存入 信息
        $res = $this->model->where(['id' => $ordersId])->update(['orders_user_id' => $userId]);

        if ($ordersId > 0) {
            //分配客服,是否指定为承机分配
            $RepositoryService = new ServiceRepository();
            $RepositoryService->randomBindServiceUser($insertData['ordersno'], $data['contact_phone'] ?? '', $data['pay_identity'] ?? '');
        }
        // 添加log 日志
        //操作日志记录
        $logDdata = [
            'orderno' => $insertData['ordersno'],
            'shop_str' => $insertData['shop_str'],
            'shop_id' => $insertData['shop_id'],
            'remark' => date('Y-m-d H:i:s') . '提交信息',
        ];
        $this->logModel->add($logDdata); // 存入操作日志
        // 添加 产品验证
        $productData = [
            'username' => $data['pay_name'],
            'idcard' => $data['pay_identity'],
            'phone' => $data['pay_phone'],
            'address' => $data['post_address'],
            'product_id' => !empty($data['product_id']) ? $data['product_id'] : '0',  //产品的id
            'shop_id' => $data['shop_id'],
        ];
        $this->productModel->add($productData); // 为了验证
        if ($res) {
            // 插入到队列中
            if (empty($insertData['status'])) {
                $this->upThree($insertData['ordersno']);
            }

            return $this->returnMsg(200, '上传成功');
        }
        return $this->returnMsg(1, '上传失败');
    }

    public function addEdit($data)
    {

        //必填 字段
        // $data['orders_user_id'] = $userId;
        if (!empty($data['orderno']) && empty($data['ordersno'])) {
            $data['ordersno'] = $data['orderno'];
        }
        $mustField = [
            'ordersno',
        ];
        $optionalFields = $this->model->getTableField();
        $msgField = [
            'ordersno' => '订单编号不能为空',
        ];
        $insertData = $this->getRealData($data, $mustField, $optionalFields, $msgField);
        if (!empty($insertData) && is_string($insertData)) {
            //返回错误参数
            return $this->returnMsg(
                2,
                $insertData
            );
        }
        // 订单表插入
        if (!empty($insertData['status'])) {
            $insertData['status_desc'] = $this->model->getOrderStatusDesc($insertData['status']);
        }
        if (!empty($insertData['shop_id_str'])) {
            // $insertData['shop_id_str'] = substr_replace('0.', '', $insertData['shop_id_str'], 1);
            $insertData['shop_id_str'] = substr_replace($insertData['shop_id_str'], '', 0, 2);
        }
        if (empty($insertData['shop_id_str'])) {
            $insertData['shop_id_str'] = $insertData['shop_id'];
        }
        if (!empty($insertData['sup_goods_id_str'])) {
            // $insertData['sup_goods_id_str'] = substr_replace('0.', '', $insertData['sup_goods_id_str'], 1);
            $insertData['sup_goods_id_str'] = substr_replace($insertData['sup_goods_id_str'], '', 0, 2);
        }
        if (empty($insertData['sup_goods_id_str'])) {
            $insertData['sup_goods_id_str'] = $insertData['goods_id'];
        }
        if (!empty($insertData['shop_name_str'])) {
            // $insertData['shop_name_str'] = substr_replace('0.', '', $insertData['shop_name_str'], 1);
            $insertData['shop_name_str'] = substr_replace($insertData['shop_name_str'], '', 0, 2);
        }
        if (empty($insertData['shop_name_str'])) {
            $insertData['shop_name_str'] = $insertData['shop_name'];
        }

        $insertData['created_at'] = date('Y-m-d H:i:s');
        $insertData['end_nums'] = 1;
        $res = $this->model->insertGetId($insertData);
        // 修改用户最后一次显示的数据
        $this->newOrdersInfo->edit(['id' => $insertData['orders_user_id']], ['orders_id' => $res, 'is_trun' => 1]);
        // 添加 产品验证
        // $productData = [
        //   'username' => $data['pay_name'],
        //   'idcard' => $data['pay_identity'],
        //   'phone' => $data['pay_phone'],
        //   'address' => $data['post_address'],
        //   'product_id' => !empty($data['product_id']) ? $data['product_id'] : '0',  //产品的id
        //   'shop_id' => $data['shop_id'],
        // ];
        // $this->productModel->add($productData); // 为了验证
        if ($res) {
            // 插入到队列中
            $this->upThree($insertData['ordersno']);
            return $this->returnMsg(200, '上传成功');
        }
        return $this->returnMsg(1, '上传失败');
    }


    //修改 用户修改
    public function editUser($data)
    {
        $where = [];
//        $this->log->info('用户信息修改查询条件:' . json_encode($where) . '修改参数:' . json_encode($params));
        $postMustFieldsMsg = [
            'id' => '请传递id参数'
        ];
        $result = $this->getRealData($data, array_keys($postMustFieldsMsg), [], $postMustFieldsMsg);
        if (!empty($result) && is_string($result)) {
            //返回错误参数
            return $this->returnMsg(
                2,
                $result
            );
        }
        $optionalFields = [
            'pay_name',
            'pay_phone',
            'pay_identity',
            'post_province',
            'post_city',
            'post_area',
            'post_address'
        ];

        $field = $this->getRealData($data, [], $optionalFields, []);
        $isTrue = $this->getOne($where);
        if (!$isTrue) {
            return $this->returnMsg(3, '您无权限修改订单信息');
        }
        $isEditData = ''; // 未修改
        $isedit = false;
        $str = '用户修改';
        if (!empty($field['pay_identity'])) {
            $str = '用户修改';
            $isEditData .= '1+'; // 用户信息修改
        }
        foreach ($field as $key => $v) {
            // 用户信息 + 商品信息 + 产品信息
            if ($key == 'goods_name' || $key == 'product_name' || $key == 'status_desc' || $key == 'pay_name' || $key == 'pay_phone' || $key == 'pay_identity' || $key == 'post_province' || $key == 'post_city' || $key == 'post_area' || $key == 'post_address' || $key == 'shop_name' || $key == 'remark') {
                if (!empty($isTrue[$key]) && $isTrue[$key] != $v) {
                    $isedit = true;
                    if ($key == 'shop_name') {
                        $str .= '分销商修改成' . $v;
                    } else {
                        $str .= $data->user->user_name . '将' . $isTrue[$key] . '修改为' . $v;
                    }
                }
            }
        }

        // 记录 修改日志
        // 添加操作日志
        $logDdata = [
            'orderno' => !empty($field['orderno']) ? $field['orderno'] : $isTrue->orderno,
            'remark' => date('Y-m-d H:i:s') . $str,
        ];
        $this->logModel->add($logDdata); // 存入操作日志
        $editOrderWhere = $where;
        $updateOrder = [];
        if (!empty($isEditData)) {
            $updateOrder = strpos($isTrue['is_edit'], $isEditData) ? $isTrue['is_edit'] : ($isTrue['is_edit'] . $isEditData);
        }
        if (!empty($updateOrder)) {
            $this->model->where($where)->update(['is_edit' => $updateOrder]);
        }
        $whereUser = [
            'id' => $isTrue['orders_user_id']
        ];
        // 修改的是用户信息
        return $this->newOrdersInfo->edit($whereUser, $data);
    }

    /**
     * Undocumented function
     *
     * @param [type] $where 修改的条件
     * @param [type] $data  修改的数据
     * @param boolean $isMust 是否返回数据
     * @param boolean $isEditTrue 是否修改上游提交的数据
     * @return void
     */
    public function edit($where, $data, $isMust = false, $isEditTrue = true, $isGoodsZTyep = 2)
    {
        // $params = $data->all();
        $params = $data;
        if (method_exists($data, 'all')) {
            $params = $data->all();
        }
        $this->log->info('用户修改订单查询条件:' . json_encode($where) . '修改参数:' . json_encode($params));
        if (empty($where)) {
            return $this->returnMsg(1, '条件不能为空');
        }
        if (empty($data)) {
            return $this->returnMsg(2, '修改参数不能为空');
        }
        $optionalFields = $this->model->getTableField();

        $field = $this->getRealData($data, [], $optionalFields, []);
        if (isset($data['status']) && ($data['status'] == 0)) {
            $field['status'] = 0;
        }
        // 查询条件
        $isTrues = $this->getOne($where);  // 查询出来的应该第一个
        if (!$isTrues) {
            return $this->returnMsg(3, '您无权限修改订单信息');
        }
        $whereEdit = ['orders_user_id' => $isTrues['orders_user_id']];
        $isTrue = $this->getOne($whereEdit);
        if (!$isTrue) {
            $isTrue = $isTrues;
        }
        // 修改商品 修改商品 或修改
        $str = ''; // 将某某数据修改成了 某某数据
        $isSubmit = false;
        $isEditData = ''; // 未修改
        $isedit = false;
        if (!empty($field['pay_identity'])) {
            $str = '用户修改';
            $isEditData .= '1+'; // 用户信息修改
        }
        if (!empty($field['goods_id'])) {
            $str = '商品信息修改';
            $isSubmit = true; // 商品信息修改
            $isEditData .= '2+';
        }
        if (!empty($field['product_id'])) {
            $str = '产品修改'; // 产品修改
            $isSubmit = true;
            $isEditData .= '3+';
        }
        if (!empty($field['goods_id'])) {
            // $resGoods = $this->goodsModel->where(['id' => $field['goods_id']])->first();
            // 商品得上架
            $resGoods = $this->goodsModel->getOne(['id' => $field['goods_id']]);
            if (empty($resGoods)) {
                return $this->returnMsg(106, '未查询到商品');
            }
            if ($resGoods->status != 0) {
                return $this->returnMsg(106, '商品已下架,请上架商品后在提交');
            }
            $field['goods_id'] = $resGoods->id;
            $field['goods_code'] = $resGoods->goods_code;
            $field['goods_name'] = $resGoods->name;
            $field['product_id'] = $resGoods->product_id;
            $field['product_name'] = $resGoods->product_name;
            $field['product_code'] = $resGoods->product_code;
            $field['sup_shop_name'] = $resGoods->sup_shop_name;
            $field['shop_name_str'] = $resGoods->shop_name_str;
            $field['sup_goods_name'] = $resGoods->sup_goods_name;
            $field['shop_id_str'] = $resGoods->shop_id_str;
            $field['sup_goods_id_str'] = $resGoods->sup_goods_id_str;
            $field['sup_shop_id'] = $resGoods->sup_shop_id;
            $field['shop_name'] = $resGoods->shop_name;
            $field['shop_str'] = $resGoods->shop_str;
            // $field['sup_goods_id'] = $resGoods->sup_goods_id;
            $field['sup_goods_id'] = $isTrue['goods_id'];
            $field['sup_goods_name'] = $isTrue['goods_name'];
            $field['sup_goods_code'] = $isTrue['goods_code'];
            $field['sup_product_code'] = $isTrue['product_code'];
            $field['sup_product_name'] = $isTrue['product_name'];
            $field['sup_product_id'] = $isTrue['product_id'];
            $field['one_product_code'] = $isTrue['one_product_code'];
            $field['one_product_name'] = $isTrue['one_product_name'];
            $field['one_product_id'] = $isTrue['one_product_id'];
            // 关联到产品信息
            if (!empty($resGoods->sup_goods_id_str)) {
                $resGoodsArr = explode('.', $resGoods->sup_goods_id_str);
                if (!empty($resGoodsArr[1])) {
                    $resGoodsProduct = $this->goodsModel->getOne(['id' => $resGoodsArr[1]]);
                    $field['product_id'] = $resGoodsProduct->product_id;
                    $field['product_name'] = $resGoodsProduct->product_name;
                    $field['product_code'] = $resGoodsProduct->product_code;
                }
            }
            // var_dump($field, 444444444);
            // 需要将上游信息清空  是否清空
            // 如果修改的是商品的话 不需要清空上游信息的
            if ($isEditTrue) {
                $field['sup_id'] = 0;
                $field['sup_name'] = '';
                $field['sup_orderno'] = '';
            }

            // var_dump($field);
        }
        if (isset($field['status'])) {
            $isedit = true;
        }
        if (isset($field['status'])) {
            $field['status_desc'] = $this->model->getOrderStatusDesc($field['status']);
        }
        // var_dump(json_decode(json_encode($isTrue), true), 222222222);
        // var_dump($field, 111111111);
        foreach ($field as $key => $v) {
            // 用户信息 + 商品信息 + 产品信息
            if ($key == 'goods_name' || $key == 'product_name' || $key == 'status_desc' || $key == 'pay_name' || $key == 'pay_phone' || $key == 'pay_identity' || $key == 'post_province' || $key == 'post_city' || $key == 'post_area' || $key == 'post_address' || $key == 'shop_name' || $key == 'remark') {
                if ($isTrue[$key] != $v) {
                    $isedit = true;
                    if ($key == 'shop_name') {
                        $str .= '分销商修改成' . $v;
                    } else {
                        $str .= !empty($data->user->user_name) ? $data->user->user_name : '' . '将' . $isTrue[$key] . '修改为' . $v . '<br/>';
                    }
                }
            }
        }
        if (!empty($field['pay_identity'])) {
            // 用户修改
            $whereEdit = [
                'id' => $isTrue['orders_user_id']
            ];
            $this->newOrdersInfo->edit($whereEdit, $data);
        }
        // var_dump($field);
        // die();
        if (!$isedit) {
            $ordernum = $isTrue['ordersno'];

//            dispatch(new OrderSubmit($ordernum, 'smsAndPushOrder', 60))->onQueue('TaskOrderSubmitDispose');

            return $this->returnMsg(200, '无修改任何数据');
        }
        // 添加操作日志
        $logDdata = [
            'orderno' => !empty($field['orderno']) ? $field['orderno'] : $isTrue['orderno'],
            'remark' => date('Y-m-d H:i:s') . $str,
        ];
        if (!empty($isEditData)) {
            $field['is_edit'] = strpos($isTrue['is_edit'], $isEditData) ? $isTrue['is_edit'] : ($isTrue['is_edit'] . $isEditData);
        }
//        if (!empty($field['orderno'])) {
//        }

        $this->logModel->add($logDdata); // 存入操作日志
        // if (isset($field['ordersno'])) {
        //   // unset($field['orderno']);
        // }
        // $field = array_merge($field, $isTrue);
        $nums = $isTrue['nums'] + 1;
        $field['ordersno'] = $isTrue['orderno'] . '-' . $nums;
        $field['orders_user_id'] = $isTrue['orders_user_id'];
        $field['nums'] = $nums;
        $field['type'] = $isGoodsZTyep;
        $field['shop_id'] = $isTrue['shop_id'];
        $field['pay_name'] = $isTrue['pay_name'];
        $field['pay_phone'] = $isTrue['pay_phone'];
        $field['pay_identity'] = $isTrue['pay_identity'];
        $field['post_address'] = $isTrue['post_address'];

        if (!empty($nums) && $nums > 5) {
            $field['status'] = 60;
            $field['three_msg'] = '转发超出限制';
        }
        // var_dump($field);
        // die();
        // var_dump($field, 1111111);
        // $res = $this->model->where($where)->update($field); //修改订单表
        $res = $this->addEdit($field); //直接生成一条新的数据订单表 // 修改或新添加
        // var_dump($res, 444444444);
        $this->log->info('状态修改修改查询条件:' . json_encode($where) . '修改参数:' . json_encode($params) . '返回结果:' . json_encode($res));
        if ($isSubmit) {
            //重新提交产品
        }
        if ($isMust && $res) {
            $resEdit = DB::table('orders')->where(['ordersno' => $isTrue['ordersno']])->update(['end_nums' => 0]);
            return $this->returnMsg(200, '修改成功', ['ordersno' => $field['ordersno']]);
        }
        if (!$isMust) {
            $resEdit = DB::table('orders')->where(['ordersno' => $isTrue['ordersno']])->update(['end_nums' => 0]);
            return $this->returnMsg(200, '修改成功', ['ordersno' => $field['ordersno']]);
        }
        return $this->returnMsg(3, '请重新修改');
    }

    public function editStatus($where, $data, $whereOr = [])
    {
        // $params = $data->all();
        $params = $data;
        if (method_exists($data, 'all')) {
            $params = $data->all();
        }
        $this->log->info('状态修改修改查询条件:' . json_encode($where) . '修改参数:' . json_encode($params));
        if (empty($where)) {
            return $this->returnMsg(1, '条件不能为空');
        }
        if (empty($data)) {
            return $this->returnMsg(2, '修改参数不能为空');
        }
        $optionalFields = $this->model->getTableField();

        $field = $this->getRealData($data, [], $optionalFields, []);
        // $isTrue = $this->model->where($where)->orWhere($whereOr)->first();
        $isTrue = $this->model->where($where)->where(function ($query) use ($whereOr) {
            if (!empty($whereOr)) {
                foreach ($whereOr as $key => $v) {
                    if ($key == 0) {
                        $query->where([$v]);
                    }
                    if ($key != 0) {
                        $query->orWhere([$v]);
                    }
                }
            }
        })->first();
        // $sql = DB::getQueryLog();
        // var_dump($sql,55555555555);
        if (!empty($field['status'])) {
            $field['status_desc'] = $this->model->getOrderStatusDesc($field['status']);
        }
        // $res =  $this->model->where($where)->orWhere($whereOr)->update($field);
        $res = $this->model->where($where)->where(function ($query) use ($whereOr) {
            if (!empty($whereOr)) {
                foreach ($whereOr as $key => $v) {
                    if ($key == 0) {
                        $query->where([$v]);
                    }
                    if ($key != 0) {
                        $query->orWhere([$v]);
                    }
                }
            }
        })->update($field);
        $this->log->info('状态修改修改查询条件:' . json_encode($where) . '修改参数:' . json_encode($params) . '返回结果:' . $res);
        if (!empty($field['status']) && $field['status'] != $isTrue->status) {
            // 推送消息
            $orders = [
                'ordersno' => $isTrue->ordersno,
            ];
            dispatch(new OrderSubmit($orders, 'smsAndPushOrder', 60))->onQueue('TaskOrderSubmitDispose');
        }

        if ($res) {
            return $this->returnMsg(200, '修改成功');
        }
        return $this->returnMsg(100, '修改失败');
    }

    // 系统修改  修改订单的物流信息 和订单状态
    public function editThree($where, $data, $isChannel = true)
    {
        $params = $data;
        if (method_exists($data, 'all')) {
            $params = $data->all();
        }

        $this->log->info('订单修改修改查询条件:' . json_encode($where) . '修改参数:' . json_encode($params));
        if (empty($where)) {
            return $this->returnMsg(1, '条件不能为空');
        }
        if (empty($data)) {
            return $this->returnMsg(2, '修改参数不能为空');
        }
        $wheres = [];
        if (!empty($where['orderno'])) {
            // $where['ordersno'] = $where['orderno'];
            $wheres['ordersno'] = $where['orderno'];
            unset($where['orderno']);
        }
        $wheres = array_merge($where, $wheres);
        $optionalFields = $this->model->getTableField();
        $field = $this->getRealData($data, [], $optionalFields, []);
        //先查询是否存在
        $isTrue = $this->getOne($wheres);
        if (!$isTrue) {
            return $this->returnMsg(3, '您无权限修改订单信息');
        }
        // 防止重复修改订单状态   1 50
        if (!empty($field['status']) && !empty($isTrue['status']) && $field['status'] <= $isTrue['status'] && $isTrue['status'] <= 40) {
            return $this->returnMsg(200, '该状态已提交过了');
        }
        // var_dump($isChannel, 5555555555);
        if (!empty($field['status']) && $field['status'] >= 50 && !$isChannel) {

            // 提交到第三方 重新提交到三方
            dispatch(new OrderSubmit($isTrue['ordersno'], 'createOrder'))->onQueue('TaskOrderSubmitDispose');
        }

        $str = '修改';
        if (!empty($field['status'])) {
            $field['status_desc'] = $this->model->getOrderStatusDesc($field['status']);
            $str .= $field['status_desc'];
        }


        $logDdata = [
            'orderno' => $isTrue['orderno'],
            'remark' => date('Y-m-d H:i:s') . $str,
        ];
        // var_dump($logDdata);
        $this->logModel->add($logDdata); // 存入操作日志
        // 修改  // 记录时间  不用设置 提交到第三方的时间
        // if (!empty($field['status']) && $field['status'] == 1) {
        //   $field['three_time_at'] = date('Y-m-d H:i:s');
        // }
        if (!empty($field['status']) && $field['status'] == 20) {
            $field['deliver_at'] = date('Y-m-d H:i:s');
        }
        if (!empty($field['status']) && $field['status'] == 30) {
            $field['sign_at'] = date('Y-m-d H:i:s');
        }

        if (!empty($field['status']) && $field['status'] == 40 && empty($field['activat_at'])) {
            $field['activat_at'] = date('Y-m-d H:i:s');
        }
        if (!empty($data['activat_at'])) {
            $field['activat_at'] = $data['activat_at'];
        }
        if (empty($field['activat_at'])) {
            unset($field['activat_at']);
        }
//        $this->log->info('订单修改数据:' . json_encode($field));

        $res = $this->model->where($wheres)->update($field); //修改订单表
//        $this->log->info('订单修改SQL:' . $this->getLastSql());
        // $field['order_id'] = $isTrue->id;

        // $this->model->edit(['order_id' => $isTrue->id], $field); // 为了统计
        if ($res) {
            return $this->returnMsg(200, '修改成功', ['orderno' => $isTrue['ordersno']]);
        }
        return $this->returnMsg(101, '修改失败');
    }

    //列表查询
    public function lists($where = [], $page = 1, $limit = 10)
    {
        $res = $this->search($this->model, $where, $page, $limit);

        return $res;
    }

    public function getOne($where, $field = ['*'], $whereOr = [], $wheres = [], $whereOrTwo = [])
    {
        // 查询到的是 最后一个数据  例如条件是: orderno 查询到的是最后一个
        if (!empty($where['ordersno'])) {
            $where['orders.ordersno'] = $where['ordersno'];
            unset($where['ordersno']);
        }
        if (!empty($where['orderno'])) {
            $where['orders_user.orderno'] = $where['orderno'];
            unset($where['orderno']);
        }
        if (!empty($where['dist_orderno'])) {
            $where['orders_user.dist_orderno'] = $where['dist_orderno'];
            unset($where['dist_orderno']);
        }
//        if (!empty($whereOr)) {
//        }
        if (!empty($wheres)) {
            $res = $this->model->where($where)->where(function ($query) use ($wheres, $whereOr, $whereOrTwo) {
                if (!empty($wheres)) {
                    $query->where($wheres);
                }
                if (!empty($whereOr)) {
                    $query->orWhere($whereOr);
                }

                if (!empty($whereOrTwo)) {
                    $query->orWhere($whereOrTwo);
                }
            })->select($field)->orderBy('orders.id', 'desc')->leftJoin('orders_user', 'orders_user.id', '=', 'orders.orders_user_id')->first();
        } else {
            $res = $this->model->where($where)->orWhere($whereOr)->select($field)->orderBy('orders.id', 'desc')->leftJoin('orders_user', 'orders_user.id', '=', 'orders.orders_user_id')->first();
        }
        if (($res)) {
            return json_decode(json_encode($res), true);
        }
        return $res;
    }

    //下单
    public function orderSubmit()
    {
    }
    // 处理订单的状态
    // 订单的状态 1: 返回的物流等信息 修改 2: 状态修改
    public function editOrderStatus($data)
    {
    }

    // 获取订单状态 和来源
    public function getOrderStatus()
    {
        $data = $this->model->orderStatus();
        $datas = [];
        foreach ($data as $key => $v) {
            $datas[] = [
                'id' => $key,
                'value' => $v
            ];
        }
        return $this->returnMsg(200, '查询成功', $datas);
    }

    public function getOneOrderStatus($status = '')
    {
        $data = $this->model->orderStatus();
        if (isset($status)) {
            return $data[$status];
        }
        return $data;
    }

    public function getOneExpressStatus($status = '')
    {
        $data = $this->model->expressStatus();
        if (isset($status)) {
            return $data[$status];
        }
        return $data;
    }

    // 来源
    public function getOrderSource()
    {
        $data = $this->model->getSourceType();
        $datas = [];
        foreach ($data as $key => $v) {
            $datas[] = [
                'id' => $key,
                'value' => $v
            ];
        }
        return $this->returnMsg(200, '查询成功', $datas);
    }

    // 来源解释
    public function getOneOrderSource($type)
    {
        $data = $this->model->getSourceType();
        if (isset($type)) {
            return $data[$type];
        }
        return $data;
    }

    //异步的时候 提交到第三方
    public function upThree($ordernum = '', $type = '')
    {
        if (empty($type)) {
            dispatch(new OrderSubmit($ordernum, 'createOrder'))->onQueue('TaskOrderSubmitDispose');
        }
        if (!empty($type)) {
            $time = 60 * 60 * 4;
            // Queue::later(Carbon::now()->addMinutes(10), new OrderSubmit($ordernum, 'createOrder'));
            dispatch(new OrderSubmit($ordernum, 'createOrder', $time))->onQueue('TaskOrderSubmitDispose');
        }
        return 1;
    }

    // 修改分销商  订单修改分销商的操作
    public function editDistAll($array = [])
    {

        if (empty($array['dist_id'])) {
            return $this->returnMsg(101, '分销商不能为空');
        }
        // 1: 检验是否是分销商
        // 2:
        if (empty($array['goodsAllid'])) {
            return $this->returnMsg(102, '修改订单信息不能为空');
        }
        foreach ($array['goodsAllid'] as $key => $v) {
            $where = [
                'orders.id' => $v
            ];
            // 查询的是订单
            $ordersArr = $this->getOne($where);
            $goods_id = $ordersArr['goods_id'];
            $res = $this->editDistOne($v, $array['dist_id'], $goods_id);
            if (!empty($res['code']) && $res['code'] != 200) {
                break;
            }
        }
        if (!empty($res)) {
            return $res;
        }
        return $this->returnMsg(200, '修改成功', []);
    }

    /**
     * Undocumented function
     *
     * @param [type] $dist_id 分销商id
     * @param [type] $goods_id  供应商的商品id
     * @return void
     */
    public function editDistOne($orderid, $dist_id, $goods_id, $editData = [])
    {
        // 查询分销商的商品
        $where = [
            'shop_id' => $dist_id,
            'sup_goods_id' => $goods_id
        ];
        // 查询出来商品信息
        // var_dump($where);

        $goodsData = $this->goodsModel->getOne($where);
        // var_dump($goodsData);
        if (!($goodsData)) {
            return $this->returnMsg(100, '未查询到商品信息');
        }
        // 然后修改商品信息
        $update = [
            'shop_id' => $dist_id,
            'goods_id' => $goodsData->id
        ];
        if (!empty($editData)) {
            $update = array_merge($update, $editData);
        }
        // 注意下商品
        // var_dump($update, 111111111);
        $editWhere = [
            'orders.id' => $orderid
        ];
        $res = $this->edit($editWhere, $update, false, false);
        return $res;
    }

    // 处理老数据
    public function editOrderUpOrders($data)
    {
        if (empty($data['ordersno'])) {
            $data['ordersno'] = $data['orderno'];
        }
        if (!empty($data['orderno'])) {
            $data['ordersno'] = $data['orderno'];
        }
        $mustField = [
            'ordersno',
        ];
        $optionalFields = $this->model->getTableField();
        $msgField = [
            'ordersno' => '订单编号不能为空',
        ];
        $insertData = $this->getRealData($data, $mustField, $optionalFields, $msgField);
        if (!empty($insertData) && is_string($insertData)) {
            //返回错误参数
            return $this->returnMsg(
                2,
                $insertData
            );
        }
        // if (!empty($insertData['status'])) {
        //   $insertData['status_desc'] = $this->model->getOrderStatusDesc($insertData['status']);
        // }
        // if (!empty($insertData['source'])) {
        //   $insertData['source_type'] = $this->model->getOrderSource($insertData['source']);
        // }
        // 订单表插入
        if (!empty($insertData['status'])) {
            $insertData['status_desc'] = $this->model->getOrderStatusDesc($insertData['status']);
        }
        if (!empty($insertData['shop_id_str'])) {
            // $insertData['shop_id_str'] = substr_replace('0.', '', $insertData['shop_id_str'], 1);
            $insertData['shop_id_str'] = substr_replace($insertData['shop_id_str'], '', 0, 2);
        }
        if (empty($insertData['shop_id_str'])) {
            $insertData['shop_id_str'] = $insertData['shop_id'];
        }
        if (!empty($insertData['sup_goods_id_str'])) {
            // $insertData['sup_goods_id_str'] = substr_replace('0.', '', $insertData['sup_goods_id_str'], 1);
            $insertData['sup_goods_id_str'] = substr_replace($insertData['sup_goods_id_str'], '', 0, 2);
        }
        if (empty($insertData['sup_goods_id_str'])) {
            $insertData['sup_goods_id_str'] = $insertData['goods_id'];
        }
        if (!empty($insertData['shop_name_str'])) {
            // $insertData['shop_name_str'] = substr_replace('0.', '', $insertData['shop_name_str'], 1);
            $insertData['shop_name_str'] = substr_replace($insertData['shop_name_str'], '', 0, 2);
        }
        if (empty($insertData['shop_name_str'])) {
            $insertData['shop_name_str'] = $insertData['shop_name'];
        }
        if (empty($insertData['created_at'])) {
            $insertData['created_at'] = date('Y-m-d H:i:s');
        }
        if (!empty($insertData['product_code'])) {
            $insertData['one_product_code'] = !empty($insertData['product_code']) ? $insertData['product_code'] : null;
        }
        if (!empty($insertData['product_name'])) {
            $insertData['one_product_name'] = !empty($insertData['product_name']) ? $insertData['product_name'] : null;
        }
        if (!empty($insertData['product_id'])) {
            $insertData['one_product_id'] = !empty($insertData['product_id']) ? $insertData['product_id'] : null;
        }
        $ordersId = $this->model->insertGetId($insertData);
        // 先添加 orders 然后在添加 orders_info
        $data['orders_id'] = $ordersId;
        // 记录用户的信息
        $userArr = $this->newOrdersInfo->add($data);
        $userId = 0;
        if (!empty($userArr['code']) && $userArr['code'] == 200) {
            $userId = $userArr['data']['id'];
        }
        if (empty($userArr['code']) || $userArr['code'] != 200) {
            return $userArr;
        }
        // 将 order里面存入 信息
        $res = $this->model->where(['id' => $ordersId])->update(['orders_user_id' => $userId]);
        if ($res) {
            // 插入到队列中
            // $this->upThree($insertData['ordersno']);
            return $this->returnMsg(200, '上传成功');
        }
        return $this->returnMsg(1, '上传失败');
    }

    public function varOrderUpOrders($data)
    {
        $where = [];
        if (!empty($data['orderno'])) {
            $where['orders.ordersno'] = $data['orderno'];
        }
        $isTrue = $this->getOne($where);
        // var_dump($isTrue);
        if (empty($isTrue)) {
            return $this->editOrderUpOrders($data);
        }
        $whereUser = ['id' => $isTrue['orders_user_id']];
        // 判断创建时间
        $isUser = $this->newOrdersInfo->getOne($whereUser);
        $isUser = json_decode(json_encode($isUser), true);
        // var_dump($isUser);
        $isEditUser = false;
        $res = ['status' => '200', 'msg' => '数据没问题'];
        if (empty($isUser)) {
            $res = ['status' => '200', 'msg' => '数据遗漏'];
        }
        if (!empty($isUser)) {
            if (!empty($data['dist_orderno']) && $isUser['dist_orderno'] != $data['dist_orderno']) {
                // 说明这条数据有问题
                // $this->newOrdersInfo->edit($whereUser, $data);
                $isEditUser = true;
            }
            if ($isUser['pay_identity'] != $data['pay_identity']) {
                $isEditUser = true;
            }
            if (strtotime($data['created_at']) != strtotime($isUser['created_at'])) {
                $isEditUser = true;
            }
            // var_dump($isEditUser);
            if ($isEditUser) {
                $res = $this->newOrdersInfo->edit($whereUser, $data);
            }
        }

        return $res;
        if ($res) {
            // 插入到队列中
            // $this->upThree($insertData['ordersno']);
            return $this->returnMsg(200, '上传成功');
        }
        return $this->returnMsg(1, '上传失败');
    }

    // 跑激活时间数据和发货时间的数据
    public function editOrderAct($where, $field)
    {
        if (empty($where)) {
            return $this->returnMsg(100, '未查询到条件');
        }
        if (empty($field)) {
            return $this->returnMsg(101, '未传递需要修改的数据');
        }
        $isTrue = $this->model->where($where)->update($field);
        if ($isTrue) {
            return $this->returnMsg(200, '修改成功');
        }
        return $this->returnMsg(102, '修改失败');
    }

    // 按照订单号 处理 如果超过两条 执行删除
    public function isManyOrder($where)
    {
        return $this->model->where($where)->count();
    }

    // 只查询订单
    public function getOneOrder($where, $field = ['*'])
    {
        return $this->model->where($where)->select($field)->first();
    }
}
